import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import SelfProcess from '@/components/useRouteCom/SelfProcess.vue'
import { render, createVNode } from 'vue'
import { constantRoutes } from './constantRouter.ts'
import getUserInfo from '@/stores/modules/user.ts'




const router = createRouter({
  scrollBehavior:()=>({
    // 路由切换时滚动到顶部
    top: 0,
    left: 0,
  }),
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [...constantRoutes],
})


//创建虚拟dom 并挂载
const vnode = createVNode(SelfProcess)
render(vnode, document.body)
// const whitelist = ['/']
router.beforeEach((to, from,next) => {
  const UserInfo = getUserInfo()
  const token= UserInfo.token
  //模拟 NProgress.start()
  // vnode?.component?.exposed.startloading()
  // //监听hash模式下的路由 createWebHashHistory
  // window.addEventListener("hashchange", function(e) {
  //   console.log(e)
  // })
  // //监听history模式下的路由跳转 createWebHistory
  // window.addEventListener("popstate", (e) => {
  //   console.log(e)
  // })
  // if(whitelist.indexOf(to.path) === -1||localStorage.getItem('token') === undefined) {
  //   next('/')
  // }else{
  //   next()
  // }
  //防止路由重定向导致的堆栈溢出
  if(token||to.path === '/login'){
    // 如果有token，放行
    next()
  }else{
    next({path:'/login'})
  }
})

router.afterEach((to, from) => {
  // vnode?.component?.exposed.endloading()
  console.log(to.path, from, 'aftereach')
})

export default router
